package org.babygo.connect.handler.server.msg;

import java.io.File;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.babygo.connect.NettyFileOperator;
import org.babygo.connect.client.NettyClient;
import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.babygo.connect.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Sharable
public class ServerFileAcceptedboundHandler extends ChannelInboundHandlerAdapter {
	private Logger log = LoggerFactory.getLogger(ServerFileAcceptedboundHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof GetAndSendFileRequest){
			log.info("收到来自客户端准备接受文件的请求");
			GetAndSendFileRequest req = (GetAndSendFileRequest) msg;
			log.info("客户端想要的文件的名称为:" + req.getFileName());
			String[] ipAndPort = CommonUtil.getIpAndPort(ctx.channel().remoteAddress());
			File f = NettyFileOperator.readyToSendFiles.get(req.getFileName());
			if (f !=null){
				log.info("开始发送到客户端的地址..." + ipAndPort[0] + ":" + req.getPort());
				NettyClient client = new NettyClient();
				if (!client.connectClient(ipAndPort[0], Integer.parseInt(req.getPort()))){
					log.info("连接失败!");
					return;
				}
				req.setFile(f);
				client.sendFile(req);
				log.info("发送完毕...");
				return;
			}
		} else log.info("暂时处理不了类似请求");
	}
}
